package com.wyan.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wyan.wiki.domain.Category;
import com.wyan.wiki.domain.CategoryExample;
import com.wyan.wiki.mapper.CategoryMapper;
import com.wyan.wiki.req.CategoryQueryReq;
import com.wyan.wiki.req.CategorySaveReq;
import com.wyan.wiki.resp.CategoryQueryResp;
import com.wyan.wiki.resp.PageResp;
import com.wyan.wiki.util.CopyUtil;
import com.wyan.wiki.util.SnowFlake;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class CategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<CategoryQueryResp> list(CategoryQueryReq req) {
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();
        categoryExample.setOrderByClause("sort asc");

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);


        /*List<CategoryResp> respList = new ArrayList<>();
        for (Category category : categoryList) {
            CategoryResp categoryResp = new CategoryResp();
            因为不想一个个的写get和set，所以这个方法被放弃了
            categoryResp.setId(category.getId());
            BeanUtils.copyProperties(category,categoryResp);
            CategoryResp categoryResp = CopyUtil.copy(category, CategoryResp.class);
            respList.add(categoryResp);

        }*/
        PageInfo<Category> pageInfo = new PageInfo<>(categoryList);

        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList, CategoryQueryResp.class);

        PageResp<CategoryQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public List<CategoryQueryResp> all() {
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);

        List<CategoryQueryResp> list = CopyUtil.copyList(categoryList,CategoryQueryResp.class);

        return list;
    }

    public void save(CategorySaveReq req){
        Category category = CopyUtil.copy(req,Category.class);
        if (ObjectUtils.isEmpty(req.getId())){
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        }else {
            categoryMapper.updateByPrimaryKey(category);
        }
    }
//    public void delete(Long id) { CategoryMapper.deleteByPrimaryKey(id);}
}